<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <div class="card-title">总订单数</div>
            <div class="card-icon">
              <i class="el-icon-s-order"></i>
            </div>
          </div>
          <div class="card-body">
            <div class="card-value">{{ statistics.orderCount }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <div class="card-title">总销售额</div>
            <div class="card-icon">
              <i class="el-icon-money"></i>
            </div>
          </div>
          <div class="card-body">
            <div class="card-value">¥{{ statistics.totalSales.toFixed(2) }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <div class="card-title">用户数量</div>
            <div class="card-icon">
              <i class="el-icon-user"></i>
            </div>
          </div>
          <div class="card-body">
            <div class="card-value">{{ statistics.userCount }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <div class="card-title">商品数量</div>
            <div class="card-icon">
              <i class="el-icon-goods"></i>
            </div>
          </div>
          <div class="card-body">
            <div class="card-value">{{ statistics.productCount }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>订单统计</span>
            <div>
              <span class="today-stats">今日订单: {{ statistics.todayOrderCount }}</span>
            </div>
          </div>
          <div class="chart-container">
            <v-chart :options="orderChartOption" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>销售额统计</span>
            <div>
              <span class="today-stats">今日销售: ¥{{ statistics.todaySales.toFixed(2) }}</span>
            </div>
          </div>
          <div class="chart-container">
            <v-chart :options="salesChartOption" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>热销商品排行</span>
          </div>
          <div class="chart-container">
            <v-chart :options="productRankOption" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>订单状态分布</span>
          </div>
          <div class="chart-container">
            <v-chart :options="orderStatusOption" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getOrderStats } from '@/api/order'
import ECharts from 'vue-echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/bar'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import 'echarts/lib/component/legend'

export default {
  name: 'Dashboard',
  components: {
    'v-chart': ECharts
  },
  data() {
    return {
      statistics: {
        userCount: 0,
        orderCount: 0,
        totalSales: 0,
        productCount: 0,
        todayOrderCount: 0,
        todaySales: 0,
        pendingOrderCount: 0
      },
      orderCountByDay: [],
      salesByDay: [],
      orderCountByStatus: [],
      hotProducts: []
    }
  },
  computed: {
    orderChartOption() {
      const xAxisData = this.orderCountByDay.map(item => item.date)
      const seriesData = this.orderCountByDay.map(item => item.count)
      
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        series: [{
          name: '订单数',
          type: 'bar',
          data: seriesData,
          barWidth: '40%',
          itemStyle: {
            color: '#409EFF'
          }
        }]
      }
    },
    salesChartOption() {
      const xAxisData = this.salesByDay.map(item => item.date)
      const seriesData = this.salesByDay.map(item => item.amount)
      
      return {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '销售额',
          type: 'line',
          data: seriesData,
          smooth: true,
          symbolSize: 8,
          itemStyle: {
            color: '#67C23A'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(103, 194, 58, 0.3)'
              }, {
                offset: 1, color: 'rgba(103, 194, 58, 0.1)'
              }]
            }
          }
        }]
      }
    },
    productRankOption() {
      const yAxisData = this.hotProducts.map(item => item.name)
      const seriesData = this.hotProducts.map(item => item.sales_count)
      
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const item = params[0];
            const product = this.hotProducts[item.dataIndex];
            return `${product.name}<br/>销售量: ${product.sales_count}<br/>销售额: ¥${product.sales_amount.toFixed(2)}`;
          }.bind(this)
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '5%',
          top: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          minInterval: 1
        },
        yAxis: {
          type: 'category',
          data: yAxisData,
          axisLabel: {
            interval: 0
          }
        },
        series: [{
          name: '销售量',
          type: 'bar',
          data: seriesData,
          barWidth: '40%',
          itemStyle: {
            color: '#E6A23C'
          }
        }]
      }
    },
    orderStatusOption() {
      // 状态映射
      const statusMap = {
        0: '待接单',
        1: '已接单',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      };
      
      // 颜色映射
      const colorMap = {
        0: '#E6A23C', // 待接单 - 黄色
        1: '#409EFF', // 已接单 - 蓝色
        2: '#909399', // 配送中 - 灰色
        3: '#67C23A', // 已完成 - 绿色
        4: '#F56C6C'  // 已取消 - 红色
      };
      
      const data = this.orderCountByStatus.map(item => ({
        name: statusMap[item.status],
        value: item.count,
        itemStyle: {
          color: colorMap[item.status]
        }
      }));
      
      return {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: data.map(item => item.name)
        },
        series: [{
          name: '订单状态',
          type: 'pie',
          radius: ['40%', '65%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)'
          },
          labelLine: {
            show: true
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          data: data
        }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getOrderStats().then(response => {
        const data = response.data
        this.statistics = {
          userCount: data.userCount,
          orderCount: data.orderCount,
          totalSales: data.totalSales,
          productCount: data.productCount,
          todayOrderCount: data.todayOrderCount,
          todaySales: data.todaySales,
          pendingOrderCount: data.pendingOrderCount
        }
        this.orderCountByDay = data.orderCountByDay
        this.salesByDay = data.salesByDay
        this.orderCountByStatus = data.orderCountByStatus
        this.hotProducts = data.hotProducts
      })
    }
  },
  beforeRouteEnter(to, from, next) {
    const userRole = localStorage.getItem('userRole')
    if ((userRole || '').toLowerCase() !== 'admin') {
      next('/404')
    } else {
      next()
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  color: #606266;
}

.card-icon {
  font-size: 24px;
  color: #409EFF;
}

.card-body {
  margin-top: 20px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 420px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.today-stats {
  font-size: 14px;
  color: #606266;
}

.chart-container {
  height: 360px;
  width: 100%;
}

/* 确保ECharts实例能够正确渲染 */
.echarts {
  width: 100% !important;
  height: 100% !important;
}
</style> 